<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="1、Java引用的类型强引用、软引用(java.lang.ref.SoftReference)、弱引用(java.lang.ref.WeakReference)、虚引用(　java.lang.ref.PhantomReference　)。 java默认的引用类型为强引用，比如 Object a &#x3D; new Object();其中 a 为强引用，new Object()为一个具体的对象。 至于软应用">
<meta property="og:type" content="article">
<meta property="og:title" content="java Reference 引用学习总结">
<meta property="og:url" content="https://www.codingw.net/posts/3c69fbc4.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="1、Java引用的类型强引用、软引用(java.lang.ref.SoftReference)、弱引用(java.lang.ref.WeakReference)、虚引用(　java.lang.ref.PhantomReference　)。 java默认的引用类型为强引用，比如 Object a &#x3D; new Object();其中 a 为强引用，new Object()为一个具体的对象。 至于软应用">
<meta property="og:locale">
<meta property="og:image" content="">
<meta property="article:published_time" content="2020-09-11T15:12:35.000Z">
<meta property="article:modified_time" content="2021-04-26T12:13:32.911Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/3c69fbc4.html"/>





  <title>java Reference 引用学习总结 | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/3c69fbc4.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">java Reference 引用学习总结</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-09-11T23:12:35+08:00">
                2020-09-11
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/3c69fbc4.html" class="leancloud_visitors" data-flag-title="java Reference 引用学习总结">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><h2 id="1、Java引用的类型"><a href="#1、Java引用的类型" class="headerlink" title="1、Java引用的类型"></a>1、Java引用的类型</h2><p>强引用、软引用(java.lang.ref.SoftReference)、弱引用(java.lang.ref.WeakReference)、虚引用(　java.lang.ref.PhantomReference　)。</p>
<p>java默认的引用类型为强引用，比如 Object a = new Object();其中 a 为强引用，new Object()为一个具体的对象。</p>
<p>至于软应用，弱引用，虚引用，就是 JAVA 虚拟机管理对象的范畴了，可以这样理解，SoftReference、WeakReference、PlantomReference 只是一种标记，JAVA 虚拟机在垃圾回收时，对上述不同的标记【引用的对象】采取不同的措施。采取措施如下：</p>
<ul>
<li><p>软引用(SoftReference)：当内存足够时，该引用【引用的对象】不会被回收，那什么是内存足够呢？进行年轻代的垃圾回收不会触发SoftReference所指向对象的回收,如果触发Full GC，那SoftReference所指向的对象将被回收。</p>
</li>
<li><p>弱引用(WeakReference) :当进行年轻代垃圾回收时，该引用指向的对象，就会被回收。</p>
</li>
<li><p>虚引用(PhantomeReference) 该引用指向的对象，无法对垃圾收集器收集对象时产生任何影响，唯一有用的是，如果被垃圾收集器收集的对象，被PhantomeReference标记，垃圾收集器会通过注册在PhantomeReference上的队列来通知应用程序，该引用指向的对象，已经被垃圾收集器回收。</p>
</li>
</ul>
<p>从上文的描述，也清楚的知道，上述应用是直接JVM打交道，更直接的说是与垃圾回收器直接的交互。</p>
<span id="more"></span>

<h2 id="2、java-lang-ref-Reference-详解"><a href="#2、java-lang-ref-Reference-详解" class="headerlink" title="2、java.lang.ref.Reference 详解"></a>2、java.lang.ref.Reference 详解</h2><h4 id="2-1-关键数据结构"><a href="#2-1-关键数据结构" class="headerlink" title="2.1 关键数据结构"></a>2.1 关键数据结构</h4><ul>
<li><p>private T referent;     /* Treated specially by GC */</p>
</li>
<li><p>private ReferenceQueue&lt;? super T&gt; queue;</p>
</li>
<li><p>private Reference next;<br>非常关键：Reference 本身可以当场一个 Reference 链表使用，在 ReferenceHandler 线程中从 pending 队列中，取出一个Reference, 如果该 Reference 相关的 queue 不为null,则执行入队操作，r.queue.enqueue(r); 参数为当前的引用，在入队列操作时，只要第一次进入队列，该引用的queue会被设置为 ReferenceQueue.ENQUEUE,也就算是再次调用进入队列操作，此时也无法再次与构造方法中传入的队 列绑定  在一起了。</p>
</li>
<li><p>private static Reference pending = null<br>关键中的关键；此队列维护着需要进入通知队列的引用，由 JVM 虚拟机垃圾回收器在检测到被引用指向的对象可达性发生改变后，如果该对象的引用（Referecnce）注册了引用队列 (ReferenceQueue),则 JVM 虚拟机垃圾收集器会将该引用加入到 pending 队列，注意这个 pending 队列是一个静态类变量。</p>
<p>为了便于理解上述的观点，先展示一下引用如何使用。</p>
<p>SoftReference sf = new SoftReference( new Object() );</p>
<p>其中sf 为引用，new Object为 sf指向的对象，其实也就是建立了 sf 到 new Object 对象的引用（关联），然后垃圾回收器发现 new Object 的可达性发生变化（其实就是变为不可达后），此时JVM虚拟机会根据引用对象 sf 的 queue 是否为空，如果为空，则直接将引用的状态变为 InActivie(非激活，离真正回收不远了)</p>
</li>
<li><p>ReferenceQueue queue = new ReferenceQueue();<br>  如果 SoftReference sf2 = new SoftRerence( new Object(),  queue );如果垃圾回收器检测到 new Object 的可达性发生变化后，会将该引用添加到 pending 引用链上，然后有专门的线程 ReferenceHandle 线程来将引用加入到引用链中（入队），也就是应用程序可以从 queue 中获取到所以垃圾回收器回收的对象的应用，也就是 queue是 垃圾回收器通知应用程序 被引用指向的对象已经被垃圾回收的消息。</p>
</li>
</ul>
<h4 id="2-2-Reference-的状态"><a href="#2-2-Reference-的状态" class="headerlink" title="2.2 Reference 的状态"></a>2.2 Reference 的状态</h4><ul>
<li><p>Active<br>激活状态（可达），一般新建的引用就是该状态，该状态的属性特点  next = null; queue = ReferenceQueue.Null(默认值) 或者  构造方法指定的 queue  Reference( T referent, ReferenceQueue queue)。</p>
<p>当垃圾回收器检测到可达性发生变化（变为不可达时），如果 queue == ReferenceQueue.Null 的话，状态直接变为 InActive, 如果 queue 不为空，则加入到 Reference 的静态变量 pending 的队列中，并将状态设置为 Pending。</p>
</li>
<li><p> Pending</p>
</li>
</ul>
<p>  会有一个专门的线程 ReferenceHandler 来处理pengding链表中的引用[pending链表，应该是后进先出的特点]，将该引用入队（如果有注册队列，也可以看出是垃圾回收器以此来通知应用程序做些事情【请参考 WeakHashMap 的实现】）。在r.queue.enque(r) 方法中，有个关键点，保证一个引用，只能入队一次，入队后，该引用就与原来的引用队列失去关联；为了清晰展示次过程，将该代码附加上（来源于 java.lang.ref.Reference）。</p>
  <figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">boolean enqueue(Reference&lt;? extends T&gt; r) &#123; &#x2F;* Called only by Reference class *&#x2F;</span><br><span class="line">        synchronized (r) &#123;</span><br><span class="line">            if (r.queue &#x3D;&#x3D; ENQUEUED) return false; &#x2F;&#x2F;关注这里</span><br><span class="line">            synchronized (lock) &#123;</span><br><span class="line">                r.queue &#x3D; ENQUEUED;                &#x2F;&#x2F; 关注这里</span><br><span class="line">                r.next &#x3D; (head &#x3D;&#x3D; null) ? r : head;</span><br><span class="line">                head &#x3D; r;</span><br><span class="line">                queueLength++;</span><br><span class="line">                if (r instanceof FinalReference) &#123;</span><br><span class="line">                    sun.misc.VM.addFinalRefCount(1);</span><br><span class="line">                &#125;</span><br><span class="line">                lock.notifyAll();</span><br><span class="line">                return true;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>  <img src="" alt="点击并拖拽以移动"></p>
<ul>
<li><p>Enqueue<br>进入队列中的Reference 中的 next 为队列中一个引用，或等于this(表示当前引用为最后一个), queue = ReferenceQueue.ENQUEUE。</p>
</li>
<li><p>InActive</p>
<p>queue = ReferenceQueue.NULL; next = this</p>
</li>
</ul>
<p>JAVA 四种引用的理解就到这了，其实 JAVA 中还有一种引用，java.lang.ref.FinalReference 应用，不过修饰符是 default, 包访问权限，主要用于 finalizer方法的执行，请关注下一篇博文。</p>
<p>再统一聊聊 java 引用中涉及到的引用的几个队列。</p>
<p>Reference中涉及到的队列(链表)</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Reference next;</span><br><span class="line"></span><br><span class="line">private static Reference pending &#x3D; null;</span><br><span class="line"></span><br><span class="line">private ReferenceQueue queue;</span><br></pre></td></tr></table></figure>

<p>每个引用可以关联一个引用队列，该引用队列由应用程序创建的，，然后垃圾回收器在检测到引用不可达时，将该引用加入到该队列，应用程序可以根据该引用队列来做些处理。（也就是该引用队列 成为 垃圾回收器与应用程序的通信机制）。</p>
<p>ReferenceQueue 自身的结构</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">private volatile Reference&lt;? extends T&gt; head &#x3D; null;</span><br></pre></td></tr></table></figure>

<p>首先，应用程序如下使用引用：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">public class TestReference &#123;</span><br><span class="line"></span><br><span class="line">           private static ReferenceQueue aQueue &#x3D; new ReferenceQueue();</span><br><span class="line"></span><br><span class="line">           public static void main(String args) &#123;</span><br><span class="line"></span><br><span class="line">                  Object a &#x3D; new Object();   &#x2F;&#x2F; 代码1</span><br><span class="line"></span><br><span class="line">                  WeakReference ref &#x3D; new WeakReference( a, aQueue );  </span><br><span class="line"></span><br><span class="line">           &#125;</span><br><span class="line"></span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<p>然后在程序运行过程，内存不断消耗，直至触发垃圾回收操作。此时，垃圾收集器发现 代码1处的 a 所指向的对象，只有 ref引用它，从根路径不可达，故垃圾回收器，会将 ref 引用加入到  static Reference pending 链表中。</p>
<blockquote>
<p>注意，此代码是写在JVM实现中的】</p>
</blockquote>
<p>所处理的操作无非就是</p>
<p>1、如果pending 为空，则将当前引用(ref) 设置为pengding,,并且将 ref对象的next指针指向自己； 如果pending不为空，则将当前的引用(ref)的next指向pengding,然后pengding = 当前的引用ref,所以 pengding 其实就是 一个后进新出的链表单向链表结构。</p>
<p>2、由此总结出  ref 与 pengding链表关联的第一步  由JVM垃圾回收器完成。<br>从pengding 链表中取出引用，进行入队操作。该操作由专门的线程(ReferenceHandle 线程处理)，我重点将 ReferenceHandle线程的源代码贴出已供分析。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">private static class ReferenceHandler extends Thread &#123;</span><br><span class="line">        ReferenceHandler(ThreadGroup g, String name) &#123;</span><br><span class="line">            super(g, name);</span><br><span class="line">        &#125;</span><br><span class="line">        public void run() &#123;</span><br><span class="line">            for (;;) &#123;</span><br><span class="line">                Reference r;</span><br><span class="line">                synchronized (lock) &#123;</span><br><span class="line">                    if (pending !&#x3D; null) &#123;        </span><br><span class="line">                        &#x2F;&#x2F; 如果pengding不为空，则取出pengding 的第一个引用，</span><br><span class="line">                        &#x2F;&#x2F; 然后重新设置pengding 的值（为原来的pending.next,见如下代码   a,b,c）</span><br><span class="line">                        r &#x3D; pending;                &#x2F;&#x2F; a 将pending取出，准备入队操作</span><br><span class="line">                        Reference rn &#x3D; r.next;  &#x2F;&#x2F; b 先获取原先pending 的 next</span><br><span class="line">                        pending &#x3D; (rn &#x3D;&#x3D; r) ? null : rn;  </span><br><span class="line">                        &#x2F;&#x2F; c  如果pending的next等于本身，则设在pending为空，否则为链表的下一个。</span><br><span class="line">                        &#x2F;&#x2F; 从这里更加看出 pending 是后进先出队列。</span><br><span class="line">                        r.next &#x3D; r;</span><br><span class="line">                    &#125; else &#123; </span><br><span class="line">                        &#x2F;&#x2F; 如果 pending 为空，则线程阻塞，等待垃圾回收器添加新的引用到 pending链表中</span><br><span class="line">                        try &#123;</span><br><span class="line">                            lock.wait();</span><br><span class="line">                        &#125; catch (InterruptedException x) &#123; &#125;</span><br><span class="line">                        continue;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">                &#x2F;&#x2F; Fast path for cleaners</span><br><span class="line">                if (r instanceof Cleaner) &#123;</span><br><span class="line">                    ((Cleaner)r).clean();</span><br><span class="line">                    continue;</span><br><span class="line">                &#125;</span><br><span class="line">                ReferenceQueue q &#x3D; r.queue;</span><br><span class="line">                if (q !&#x3D; ReferenceQueue.NULL) q.enqueue(r);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/26a08b7d.html" rel="next" title="Lambda表达式语法与函数式编程接口">
                <i class="fa fa-chevron-left"></i> Lambda表达式语法与函数式编程接口
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/84defd78.html" rel="prev" title="Alibaba Sentinel 限流与熔断初探(技巧篇)">
                Alibaba Sentinel 限流与熔断初探(技巧篇) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1%E3%80%81Java%E5%BC%95%E7%94%A8%E7%9A%84%E7%B1%BB%E5%9E%8B"><span class="nav-number">1.</span> <span class="nav-text">1、Java引用的类型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2%E3%80%81java-lang-ref-Reference-%E8%AF%A6%E8%A7%A3"><span class="nav-number">2.</span> <span class="nav-text">2、java.lang.ref.Reference 详解</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1-%E5%85%B3%E9%94%AE%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84"><span class="nav-number">2.0.1.</span> <span class="nav-text">2.1 关键数据结构</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-Reference-%E7%9A%84%E7%8A%B6%E6%80%81"><span class="nav-number">2.0.2.</span> <span class="nav-text">2.2 Reference 的状态</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
